package org.sundatagroup.aurora.monitor.entity.player;

import java.util.List;
import java.util.Random;

import org.sundatagroup.aurora.core.entity.IJsonEntity;
import org.sundatagroup.aurora.monitor.entity.pojo.PlayList;

import com.google.gson.JsonNull;
import com.google.gson.JsonObject;

/**
 * <p>播放器参数, 即播放列表状态
 * </p>
 * 
 * @author Zdream
 * @date 2018-05-28
 * @since 0.2.0
 */
public class PlayerParam implements IJsonEntity {

	/**
	 * 播放顺序
	 */
	private PlayerSequence sequence = PlayerSequence.LOOP;

	/**
	 * 当前正在播放的工程, 在播放列表中的索引.
	 * -1 为没有在播放
	 */
	private int current;
	
	/**
	 * 分配的播放列表, 可能为空
	 */
	private PlayList playList;
	
	/**
	 * <p>是否处于正在连续播放状态.
	 * <p>该参数说明播放列表是否在播放, 与展示屏状态中的播放状态独立
	 * <p>该参数不会向前端发布 (toJson 方法不会加入该参数)
	 * </p>
	 */
	private boolean playing = false;
	
	public PlayerSequence getSequence() {
		return sequence;
	}

	public void setSequence(PlayerSequence sequence) {
		if (sequence == null) {
			this.sequence = PlayerSequence.LOOP;
		} else {
			this.sequence = sequence;
		}
	}

	public int getCurrent() {
		return current;
	}

	public void setCurrent(int current) {
		this.current = current;
	}

	public PlayList getPlayList() {
		return playList;
	}

	public void setPlayList(PlayList playList) {
		this.playList = playList;
	}
	
	public boolean isPlaying() {
		return playing;
	}

	public void setPlaying(boolean playing) {
		this.playing = playing;
	}

	/**
	 * 选择下一个要播放的工程
	 * @param
	 *   返回要播放的工程 id.
	 *   <br>如果没有下一个要播放的工程, 返回 -1.
	 */
	public int chooseNextProject() {
		if (playList == null) {
			return current = -1;
		}
		
		switch (sequence) {
		case LOOP: {
			List<Integer> pids = playList.getProjects();
			final int len = pids.size();
			
			if (len == 0) {
				return current = -1;
			} else if (current == -1 || current >= len) {
				current = 0;
			} else {
				current = (current + 1) % len;
			}
			return pids.get(current);
		}
		
		case RANDOM: {
			List<Integer> pids = playList.getProjects();
			final int len = pids.size();
			
			if (len == 0) {
				return current = -1;
			} else {
				Random r = new Random();
				current = r.nextInt(len);
			}
			return pids.get(current);
		}
		}
		
		return -1;
	}

	@Override
	public JsonObject toJson() {
		JsonObject jo = new JsonObject();
		
		if (playList != null) {
			jo.add("playList", playList.toJson());
			jo.addProperty("current", current);
			jo.addProperty("seq", sequence.name());
		} else {
			jo.add("playList", JsonNull.INSTANCE);
			jo.addProperty("current", -1);
			jo.add("seq", JsonNull.INSTANCE);
		}
		
		return jo;
	}

}
